package leetcode_bin_tree_test;

import bin_tree.TreeNode;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 左叶子之和
 */
public class SumOfLeftLeaves {
    static int sum = 0;
    public static int sumOfLeftLeaves(TreeNode root) {
        // 深度优先搜索
//        if (root.left == null && root.right == null) {
//            return 0;
//        }
//        findLeftLeaves(root);
//        return sum;

        // 广度优先搜索
        if (root.left == null && root.right == null) {
            return 0;
        }
        int ret = 0;
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.offer(root);
        while (!deque.isEmpty()) {
            TreeNode node = deque.poll();
            // 先获取左孩子
            if (node.left != null) {
                // 判断左孩子是否是叶子节点
                TreeNode left = node.left;
                if (isLeave(left)) {
                    ret += left.val;
                } else {
                    deque.offer(left);
                }
            }
            if (node.right != null) {
                // 如果当前右孩子是叶子节点则直接不加入队列中
                TreeNode right = node.right;
                if (!isLeave(right)) {
                    deque.offer(right);
                }
            }
        }
        return ret;
    }

    public static boolean isLeave(TreeNode node) {
        return node.left == null && node.right == null;
    }

    private static void findLeftLeaves(TreeNode root) {
        if (root == null) {
            return;
        }
        TreeNode leftNode = root.left;
        // 左叶子的左孩子为空且右孩子也为空则证明值左叶子
        if (leftNode != null && leftNode.left == null && leftNode.right == null) {
            sum += leftNode.val;
        } else {
            findLeftLeaves(leftNode);
        }
        if (root.right != null) {
            findLeftLeaves(root.right);
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(3);
        TreeNode node3 = new TreeNode(4);
        TreeNode node4 = new TreeNode(5);
//        TreeNode node5 = new TreeNode(6);
        root.left = node1;
        root.right = node2;
        node1.left = node3;
        node1.right = node4;
//        node4.left = node5;
        System.out.println(sumOfLeftLeaves(root));
    }
}
